package br.com.napoleao.controlfin.core.persistence.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import br.com.napoleao.controlfin.core.persistence.factory.EntityManagerProvider;

public class CrudDAO<E>{
	
	private EntityManager em;
	
	public void insert(E entidade) {
			EntityManagerFactory emf = EntityManagerProvider.getEntityManagerFactory();
			em = emf.createEntityManager();
		
			em.getTransaction().begin();
			em.persist(entidade);
			em.getTransaction().commit();
	}
	
	
	public void update(E entidade){

		EntityManagerFactory emf = EntityManagerProvider.getEntityManagerFactory();
		em = emf.createEntityManager();
		
		em.getTransaction().begin();
		em.merge(entidade);
		em.getTransaction().commit();
	}
	
	public void delete(Object id, Class<E> clazz){
		
		EntityManagerFactory emf = EntityManagerProvider.getEntityManagerFactory();
		em = emf.createEntityManager();
		
		em.getTransaction().begin();
		em.remove(em.find(clazz, id));
		em.getTransaction().commit();
	}

	public E recuperarPorId(Object id, Class<E> clazz){
		EntityManagerFactory emf = EntityManagerProvider.getEntityManagerFactory();
		em = emf.createEntityManager();
		
		em.getTransaction().begin();
		return em.find(clazz, id);
	}
	
	public List<E> listAll(Class<E> clazz){
		EntityManagerFactory emf = EntityManagerProvider.getEntityManagerFactory();
		em = emf.createEntityManager();
		
		String hql = "from "+clazz.getSimpleName();
		em.getTransaction().begin();
		return em.createQuery(hql).getResultList();
	}

	public List<E> listAll(Class<E> clazz, String orderBy, String ascDesc) {
		EntityManagerFactory emf = EntityManagerProvider.getEntityManagerFactory();
		em = emf.createEntityManager();
		
		String hql = "from "+clazz.getSimpleName()+" order by "+orderBy+" "+ascDesc;
		em.getTransaction().begin();
		return em.createQuery(hql).getResultList();
	}
}

